package ckw.gui;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import ckw.database.AdministratorToken;
import ckw.database.DatabaseManager;
import ckw.database.Election;
import ckw.database.OKW;
import ckw.database.OKWMember;
import ckw.database.OKW_Election;

import core.modules.Printer;

public class PrintTokens {
	Shell shell = null;
	Group dane = null;
	
	public PrintTokens(Shell parent, String electionName){
		shell  = new Shell(parent, SWT.TITLE|SWT.SYSTEM_MODAL| SWT.CLOSE | SWT.MAX);
		init(electionName);
		MainWindowC.center(shell);
		shell.open();
	}
	
	private void init(final String electionName){
		dane = new Group(shell, SWT.NONE); 
		
		Button button = new Button(dane, SWT.PUSH);
		button.setText("Drukuj");
		button.setLocation(0,0);
		button.pack();
		
		button.addSelectionListener(new SelectionListener() {
			
			public void widgetSelected(SelectionEvent arg0) {
				DatabaseManager db = DatabaseManager.getInstance();
				Election election = db.getElection(electionName);
				Set<AdministratorToken> tokens = election.getAdministratorTokens();
				Set<OKW_Election> okwsE = election.getOkw_elections();
				ArrayList<String> data = new ArrayList<String>(); 
				
				for(AdministratorToken at: tokens){
					OKWMember mem = at.getOkwmember();
					mem = db.get(OKWMember.class, mem.getId());
					Set<OKW> okws = mem.getOkws();
					OKW okwW = null;
					
					for(OKW o: okws){
						for(OKW_Election oe: okwsE){
							
							if(oe.getOkw().getId().equals(o.getId()));
							okwW = o;
						}
					}

					String tmp = okwW.getName() + " " + at.getOkwmember().getName() + " " +
							at.getOkwmember().getSurname() + " " + at.getValue();
					
					data.add(tmp);
					
				}
				Collections.sort(data, new Comparator<String>(){

					@Override
					public int compare(String o1, String o2) {
						return o1.compareTo(o2);
					}
				});
				
				String[] str = new String[data.size()];
				data.toArray(str);
				Printer printer = new Printer();
				printer.drukuj(str);
				shell.close();
			}
			
			public void widgetDefaultSelected(SelectionEvent arg0) {
			}
		});
		
		dane.pack();
		shell.pack();
	}

}
